package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.common.util.RequestUtils;
import com.mars.common.util.TokenUtils;
import com.mars.module.admin.entity.SysDictData;
import com.mars.module.admin.entity.SysHouse;
import com.mars.module.admin.entity.SysHouseRentRecord;
import com.mars.module.admin.mapper.SysDictDataMapper;
import com.mars.module.admin.mapper.SysHouseMapper;
import com.mars.module.admin.mapper.SysHouseRentRecordMapper;
import com.mars.module.admin.request.SysHouseRentRecordRequest;
import com.mars.module.admin.service.ISysHouseRentRecordService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 租房记录业务层处理
 *
 * @author mars
 * @date 2024-01-23
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysHouseRentRecordServiceImpl implements ISysHouseRentRecordService {

    private final SysHouseRentRecordMapper baseMapper;
    private final SysDictDataMapper dictDataMapper;
    private final SysHouseMapper houseMapper;
    private final TokenUtils tokenUtils;
    private final SysUserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysHouseRentRecord add(SysHouseRentRecordRequest request) {
        SysHouseRentRecord entity = new SysHouseRentRecord();
        HttpServletRequest servletRequest = RequestUtils.getRequest();
        Long userId = tokenUtils.getUserId(servletRequest);
        entity.setHouseId(request.getHouseId());
        entity.setStartDate(request.getStartDate());
        entity.setEndDate(request.getEndDate());
        entity.setUserId(userId);
        entity.setStatus("0");
        entity.setCreateTime(LocalDateTime.now());
        baseMapper.insert(entity);
        SysHouse sysHouse = houseMapper.selectById(request.getHouseId());
        if (sysHouse != null) {
            sysHouse.setStatus("5");//审核中
            houseMapper.updateById(sysHouse);
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysHouseRentRecordRequest request) {
        SysHouseRentRecord entity = new SysHouseRentRecord();
        entity.setId(request.getId());
        entity.setHouseId(request.getHouseId());
        entity.setStartDate(request.getStartDate());
        entity.setEndDate(request.getEndDate());
        entity.setUserId(request.getUserId());
        entity.setStatus(request.getStatus());
        SysHouse sysHouse = houseMapper.selectById(request.getHouseId());
        if (sysHouse != null) {
            if ("1".equals(request.getStatus())) {
                sysHouse.setStatus("1");//已出租
            } else {
                sysHouse.setStatus("3");//已发布
            }
            houseMapper.updateById(sysHouse);
        }
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysHouseRentRecord getById(Long id) {
        SysHouseRentRecord rentRecord = baseMapper.selectById(id);
        SysHouse sysHouse = houseMapper.selectById(rentRecord.getHouseId());
        SysUser sysUser = userMapper.selectById(rentRecord.getUserId());
        rentRecord.setHouseName(sysHouse == null ? "" : sysHouse.getHouseName());
        rentRecord.setUserName(sysUser == null ? "" : sysUser.getUserName());
        return rentRecord;
    }

    @Override
    public PageInfo<SysHouseRentRecord> pageList(SysHouseRentRecordRequest request) {
        Page<SysHouseRentRecord> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysHouseRentRecord> query = this.buildWrapper(request);
        IPage<SysHouseRentRecord> pageRecord = baseMapper.selectPage(page, query);
        List<SysHouseRentRecord> records = pageRecord.getRecords();
        List<SysHouseRentRecord> recordsNew = new ArrayList<>();
        for (SysHouseRentRecord rentRecord : records) {
            SysHouse sysHouse = houseMapper.selectById(rentRecord.getHouseId());
            SysUser sysUser = userMapper.selectById(rentRecord.getUserId());
            rentRecord.setHouseName(sysHouse == null ? "" : sysHouse.getHouseName());
            rentRecord.setUserName(sysUser == null ? "" : sysUser.getUserName());
            rentRecord.setStatusName(getStatusName(rentRecord.getStatus(), "review_status"));
            recordsNew.add(rentRecord);
        }
        recordsNew = recordsNew.stream().sorted((m1, m2) -> m2.getCreateTime().compareTo(m1.getCreateTime())).collect(Collectors.toList());
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }

    private String getStatusName(String value, String type) {
        List<SysDictData> reviewStatus = dictDataMapper.selectList(Wrappers.lambdaQuery(SysDictData.class)
                .eq(SysDictData::getDictType, type).orderByAsc(SysDictData::getDictSort));
        SysDictData sysDictData = reviewStatus.stream().filter(e -> value.equals(e.getDictValue())).findFirst().orElse(null);
        return sysDictData == null ? "" : sysDictData.getDictLabel();
    }


    @Override
    public List<SysHouseRentRecord> list(SysHouseRentRecordRequest request) {
        LambdaQueryWrapper<SysHouseRentRecord> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysHouseRentRecord> buildWrapper(SysHouseRentRecordRequest param) {
        LambdaQueryWrapper<SysHouseRentRecord> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.like(SysHouseRentRecord::getStatus, param.getStatus());
        }
        if (param.getUserId() != null) {
            query.eq(SysHouseRentRecord::getUserId, param.getUserId());
        }
        return query;
    }

}
